package hash

import (
	"crypto/aes"
	"crypto/cipher"
	"encoding/base64"
)

// DecryptAES256GCM 使用 AEAD_AES_256_GCM 算法进行解密
func DecryptAES256GCM(aesKey, associatedData, nonce, ciphertext string) (plaintext string, err error) {
	decodedCiphertext, err := base64.StdEncoding.DecodeString(ciphertext)
	if err != nil {
		return "", err
	}
	c, err := aes.NewCipher([]byte(aesKey))
	if err != nil {
		return "", err
	}
	gcm, err := cipher.NewGCM(c)
	if err != nil {
		return "", err
	}
	gcm.Seal(nil, []byte(nonce), decodedCiphertext, []byte(associatedData))
	dataBytes, err := gcm.Open(nil, []byte(nonce), decodedCiphertext, []byte(associatedData))
	if err != nil {
		return "", err
	}
	return string(dataBytes), nil
}

func EncryptAES256GCM(aesKey, associatedData, nonce, ciphertext string) (plaintext string, err error) {
	//decodedCiphertext, err := base64.StdEncoding.DecodeString(ciphertext)
	//if err != nil {
	//	return "", err
	//}
	c, err := aes.NewCipher([]byte(aesKey))
	if err != nil {
		return "", err
	}
	gcm, err := cipher.NewGCM(c)
	if err != nil {
		return "", err
	}

	dataBytes := gcm.Seal(nil, []byte(nonce), []byte(ciphertext), []byte(associatedData))
	encodedCiphertext := base64.StdEncoding.EncodeToString(dataBytes)
	return encodedCiphertext, err
}
